package com.way.cloud.common.core.domain;

import com.way.cloud.common.core.enums.ResultEnum;
import com.fasterxml.jackson.annotation.JsonFormat;

import java.io.Serializable;
import java.util.Date;

public class R<T> implements Serializable {

    private String code;
    private String message;
    private T data;

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private Date timestamp;

    public static <T> R<T> ok() {
        return respResult(ResultEnum.SUCCESS);
    }

    public static <T> R<T> ok(T data) {
        return respResult(data, ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getDescription());
    }

    public static <T> R<T> ok(T data, String message) {
        return respResult(data, ResultEnum.SUCCESS.getCode(), message);
    }

    public static <T> R<T> fail(String message) {
        return respResult(null, ResultEnum.FAIL.getCode(), message);
    }

    public static <T> R<T> fail(ResultEnum resultEnum) {
        return respResult(resultEnum);
    }

    private static <T> R<T> respResult(ResultEnum resultEnum) {
        return respResult(null, resultEnum.getCode(), resultEnum.getDescription());
    }

    private static <T> R<T> respResult(T data, String code, String message) {
        R<T> result = new R<>();
        result.setCode(code);
        result.setData(data);
        result.setMessage(message);
        result.setTimestamp(new Date());
        return result;
    }

}
